//
//  PMCAdvisoryViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/7.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON
import JXSegmentedView

enum chatStatusEnum: Int, HandyJSONEnum {
    case nurse = 0,
         advisory = 1
    
    var tipTitle :String{
        switch self {
        case .nurse:
            return "您暂时还没有护理咨询订单哦～"
        case .advisory:
            return "您暂时还没有图文问诊哦～"
       
        }
    }
    var tipImage :String{
        switch self {
        case .nurse:
            return "empty_appointment"
        case .advisory:
            return "empty_advisory"
       
        }
    }

}
/// 就诊室-图文问诊
class PMCAdvisoryViewController: BaseViewController {
    
    private var page = 1
    
    var status :chatStatusEnum?
    
    var loadComplete: ((Int) -> Void)?
    
    private var viewModel: AdvisoryViewModel? {
        didSet {
            guard let vm = viewModel,
                  let tableView = tableView else { return }
            tableView.isHidden = vm.showEmptyView
            emptyView.isHidden = !vm.showEmptyView
            
            emptyView.refreshClosure = { [weak self] in
                self?.tableView.isHidden = false
                self?.emptyView.isHidden = true
                self?.tableView.mj_header?.beginRefreshing()
            }
            
            tableView.reloadData()
        }
    }
    
    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.rowHeight = 80
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.tableFooterView = UIView()
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 78, bottom: 0, right: 0)
            tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        emptyView.configure(with: UIImage(named: status?.tipImage ?? ""), title: status?.tipTitle)
        setupRefresh()
        setupNotification()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        refreshData()
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(loadData),
                                               name: NotiName.refreshData,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(receiveMessage(_:)),
                                               name: NotiName.receiveMessage,
                                               object: nil)
        // 结束咨询
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(sureEndAdvisory(_:)),
                                               name: NotiName.endAdvisory,
                                               object: nil)
    }
    
    private func setupRefresh() {
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_footer = refreshFooter(action: #selector(loadMoreData))
    }
    
    private func endRefresh() {
        guard let tableView = tableView else { return }
        tableView.mj_header?.endRefreshing()
        tableView.mj_footer?.endRefreshing()
    }

}

// MARK: - 事件监听
extension PMCAdvisoryViewController {
    /// 新建咨询

    private func refreshData() {
        page = 1
        handleData(loadMore: false)
    }
    
    @objc private func loadData() {
        page = 1
        handleData(loadMore: false)
    }
    
    @objc private func loadMoreData() {
        page += 1
        handleData(loadMore: true)
    }
    
    public func handleData(loadMore: Bool) {
        let success: (_ models: [Advisory]) -> Void = { [weak self] models in
            guard let self = self else { return }
            
            self.endRefresh()
            if !loadMore {
                self.viewModel = AdvisoryViewModel(models: models)
            } else {
                if models.count == 0 {
                    self.page -= 1
                } else {
                    self.viewModel?.loadMore(with: models)
                    if let tableView = self.tableView {
                        tableView.reloadData()
                    }
                }
            }
            
            if !loadMore {
                self.loadComplete?(models.count)
            }
        }
        
        let failure: (_ errorMsg: String?) -> Void = { [weak self] errorMsg in
            self?.endRefresh()
            if loadMore { self?.page -= 1 }
            HUDTool.showError(message: errorMsg)
        }
 
     switch status{
        case .nurse:
            AdvisoryViewModel.getNurseList(patientId: UserDefaults.userId, current: page, success: success, failure: failure)
        case .advisory:
            AdvisoryViewModel.getAdvisotyList(patientId: UserDefaults.userId, current: page, success: success, failure: failure)
        case .none:
            return
        }
    
    }
    
    @objc func receiveMessage(_ noti: Notification) {
        guard let message = noti.object as? String,
        let current = UIViewController.current(),
        current == self else { return }
        
        if let model = JSONDeserializer<ReceiveModel>.deserializeFrom(json: message) {
            if model.command == 11 ||
                model.command == 20 ||
                model.cmd == 107 ||
                model.cmd == 108 ||
                model.cmd == 208 ||
                model.cmd == 109 {
                refreshData()
            }
        }
    }
    
    @objc func sureEndAdvisory(_ noti: Notification) {
        refreshData()
    }
}

extension PMCAdvisoryViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AdvisoryViewCell.reuseIdentifier,
                                                 for: indexPath) as! AdvisoryViewCell
        if let rowVM = viewModel?.viewModel(of: indexPath) {
            cell.configure(with: rowVM)
        }
        return cell
    }
}

extension PMCAdvisoryViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(of: indexPath) else { return }
        let chatVc = ChatViewController(with: vm.diagnoseId)
        chatVc.businessType = vm.businessType
        chatVc.status = status
        chatVc.title = vm.doctor
        navigationController?.pushViewController(chatVc, animated: true)
        chatVc.handlerClosure = { [weak self] in
            guard let self = self else { return }
            self.tableView.mj_header?.beginRefreshing()
        }
    }
}

extension PMCAdvisoryViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
